package gee

import (
	"net/http"
	"fmt"
	"encoding/json"
)

type H map[string]interface{} //定义一个H类型，字典，key为string类型，value为任意类型

type Context struct {
	Writer http.ResponseWriter
	Req *http.Request
	Path string
	Method string
	StatusCode int
}

func newContext(w http.ResponseWriter,req *http.Request) *Context {
	return &Context{
		Writer:w,
		Req:req,
		Path:req.URL.Path,	
		Method:req.Method,
	}
}

//该函数是一个方法，属于Context结构体。它用于从HTTP请求的表单中获取指定键(key)的值，并返回该值作为字符串。
func (c *Context) PostForm(key string)string{
	return c.Req.FormValue(key)
}

//获取请求接口的后缀参数
func (c *Context) Query(key string) string {
	return c.Req.URL.Query().Get(key)
}

func (c *Context)Status(code int){
	c.StatusCode = code
	c.Writer.WriteHeader(code)

}
func (c *Context) SetHeader(key string,value string){
	c.Writer.Header().Set(key,value)
}
func (c *Context) String(code int , format string, value ...interface{}) {
	c.SetHeader("Content-Type","text/plain")
	c.Status(code)
	c.Writer.Write([]byte(fmt.Sprintf(format,value...)))
} 

func (c *Context) JSON(code int, obj interface{}){
	c.SetHeader("Content-Type","application/json")
	c.Status(code)
	encoder := json.NewEncoder(c.Writer)
	if err := encoder.Encode(obj);err != nil {
		http.Error(c.Writer,err.Error(),500)
	}
}